<template>
  <div>
    <!--  头部查询区-->
    <div id="div_heard">
      <el-row :gutter="20" type="flex" justify="center">
        <el-col :span="9">
          <el-input placeholder="输入关键字检索" v-model.trim="queryInfo" clearable>
            <!--            <el-button slot="append" icon="el-icon-search" @click="getQueryList"></el-button>-->
          </el-input>

        </el-col>
        <el-col :span="2  ">
          <el-button type="info" @click="dialogVisible0 = true" icon="el-icon-circle-plus-outline">
            添加链接
          </el-button>
        </el-col>
      </el-row>

      <!--      弹窗会话框-->
      <el-dialog style="padding: 0" title="新建链接" :visible.sync="dialogVisible0" @close="closeDialog('addForm')">
        <el-form :model="addForm" :rules="addFormRules" ref="addForm" style="text-align: left;">
          <el-form-item prop="url" label="地址URL" label-width="80px">
            <el-input placeholder="请输入http://xxxx 或 https://xxx" v-model="addForm.url"></el-input>
          </el-form-item>
          <el-form-item prop="title" label="名称描述" label-width="80px">
            <el-input v-model="addForm.title"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible0 = false">取 消</el-button>
    <el-button type="primary" @click="addurl">新 增</el-button>
  </span>
      </el-dialog>
    </div>


    <!--  链接卡片区-->
    <div style="display: flex;justify-content: center; ">
      <div id="listdiv">
        <div v-for="(o,index) in listdata" :key="index">
          <el-card shadow="always" :body-style="{ padding: '5px' }" @click.native="openUrl(o.url)">
<!--            <img :src=o.imgsrc class="image">-->
<!--            <div>-->
<!--              <el-tooltip :content=o.title placement="bottom" effect="light">-->
<!--                <span>{{o.title}}</span>-->
<!--              </el-tooltip>-->
<!--              <i id="more" class="el-icon-s-tools" @click="openDetails(o)" onClick="event.cancelBubble = true"></i>-->
<!--            </div>-->
             <el-row  >
             <el-col style="justify-content: center;">
                <img style="height: 80px;width: 80px" :src="imgShow(o.url)" onerror="this.src='./website.png'" />
<!--                <img style="height: 80px;width: 80px" :src="imgShow(o.url)" onerror="this.src='./_nuxt/assets/images/website.png'" />-->
<!--                 <img style="height: 80px;width: 80px" :src=o.imgsrc >-->
             </el-col>
           </el-row>

            <el-row style="color: #606266;margin-top: 6px">
              <el-col :span="18" style="justify-content: center;">
                  <el-tooltip style="margin-left: 5px" :content=o.title placement="bottom" effect="light">
                <span style="text-align: center">{{o.title}}</span>
              </el-tooltip>
              </el-col>
             <el-col style="justify-content: center;" :span="4">
                  <i id="more" class="el-icon-s-tools" @click="openDetails(o)" onClick="event.cancelBubble = true"></i>
             </el-col>

           </el-row>
          </el-card>
        </div>

      </div>
      <!--    弹出详情框-->
      <el-dialog title="详细信息" :visible.sync="dialogVisible" width="40%" @close="closeDialog('urlForm')">
        <el-form :model="urlForm" ref="urlForm" :rules="addFormRules">
          <el-form-item prop="url" label="地址URL" label-width="80px">
            <el-input v-model="urlForm.url"></el-input>
          </el-form-item>
          <el-form-item prop="title" label="名称描述" label-width="80px">
            <el-input v-model="urlForm.title"></el-input>
          </el-form-item>
        </el-form>
        <el-popconfirm title="确定删除吗？" @confirm="deleteUrl">
          <el-button type="danger" slot="reference">删 除</el-button>
        </el-popconfirm>
        <!--        <el-button type="danger" @click="deleteUrl">删 除</el-button>-->
        <el-button type="primary" @click="updateUrl">修 改</el-button>
      </el-dialog>

    </div>
  </div>
</template>

<script>
  export default {
    middleware: 'metaTitle',
    meta: {title: '主页'},
    name: "home",

    // async asyncData(context){
    //   const res = await context.$axios.get('/api/urllist').catch((error) => {
    //       context.$message.error(error)
    //     });
    //     // for (var index in res.data.result) {
    //     //   res.data.result[index].imgsrc = require(`${res.data.result[index].imgsrc}`)
    //     // }
    //    return {listdata : res.data.result}
    // },
    created() {
      this.getUrllist();
    },
    data() {
      return {

        dialogVisible0: false,
        dialogVisible: false,
        queryInfo: '',
        addForm: {title: '', url: ''},
        urlForm: {_id: '', title: '', url: ''},
        addFormRules: {
          title: [{required: true, message: '必输入描述', trigger: 'blur'}],
          url: [{required: true, message: '您没有输入链接URL', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                var matchUrl = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/
                if (!matchUrl.test(value.trim())) {
                  callback(new Error('url格式不正确！'))
                } else {
                  callback();
                }
              }, trigger: 'blur'
            }]
        },
        // listdata:[{title: '非税交换应用系统', url: 'http://baidu.com', imgsrc: require('../assets/images/website.png')}],
        listdata: [],
        listdata1: [],
      }
    },
    methods: {
      // getstore(){
      //   //编程式访问VUEX
      //   //发出actions请求给user模块
      //   this.$store.dispatch('user/A_UPDATE_USER',{err:0,msg:'登录成功',token:'aaaaa',data:{title:'actions data'}});
      //   //发出mutations请求给user模块
      //   //this.$store.commit('user/M_UPDATE_USER',{err:0,msg:'登录成功',token:'aaaaa',data:{title:'mutations data'}})
      // }
      imgShow: function (url) {
        function findStrIndex(str, cha, num) {
          num = num -1
          var x = str.indexOf(cha);
          for (var i = 0; i < num; i++) {
            x = str.indexOf(cha, x + 1);
          }
          return x;
        }
        let index = findStrIndex(url, '/', 3)
        if (index == -1) return url+'/favicon.ico'
        let src = url.substring(0, index) + '/favicon.ico'
        // let src = url+'/favicon.ico'
        return src
      },
      //关闭Dialog清空数据
      closeDialog(formName) {
        this.$refs[formName].resetFields()
      },
      async getUrllist() {
        try {
          const res = await this.$axios.get('/api/urllist').catch((error) => {
            this.$message.error(error)
          });
          for (var index in res.data.result) {
            res.data.result[index].imgsrc = require('../assets/images/' + res.data.result[index].imgsrc)
          }
          this.listdata1 = this.listdata = res.data.result
          this.queryInfo = null
        } catch (e) {

        }
        // this.listdata = res.data.result.map(item=>{
        //   return{
        //     title:item.title,
        //     imgsrc:require('../assets/images/'+item.imgsrc)
        //   }
        // })
      },
      addurl() {
        this.$refs.addForm.validate(
          async valid => {
            if (!valid) return this.$message.error('请输入正确后提交');
            try {
              const res = await this.$axios.post('/api/urllist', this.addForm);
              //console.log(res.data.result)
              if (res.status === 200 && res.data.code === "ValidationError") {
                this.$message.error("提交重复的URL或名称")
              }
              if (res.status === 200 && res.data.code === "success") {
                this.$message.success("提交成功")
              }
              this.getUrllist();
            } catch (error) {
              this.$message.error('连接服务器失败')
            }
            this.dialogVisible0 = false
          }
        )
      },
      openUrl(url) {
        window.open(url)
      },
      openDetails(item) {
        this.urlForm = null;
        this.dialogVisible = true;
        //this.urlForm = item;
        //只要id url title
        this.urlForm = {_id: item._id, url: item.url, title: item.title}
      },
      async deleteUrl() {
        try {
          const res = await this.$axios.delete('/api/urllist/' + this.urlForm._id, this.urlForm);
          console.log(res)
          if (res.status === 200 && res.data.code === "success") {
            this.$message.success("删除成功")
          }
          this.getUrllist();
        } catch (e) {

          this.$message.error('连接服务器失败')
        }
        this.dialogVisible = false
      },
      updateUrl() {
        this.$refs.urlForm.validate(
          async valid => {
            if (!valid) return this.$message.error('请输入正确后提交');
            try {
              const res = await this.$axios.put('/api/urllist/' + this.urlForm._id, this.urlForm);
              if (res.status === 200 && res.data.code === "ValidationError") {
                this.$message.error("提交重复的URL或名称")
              }
              if (res.status === 200 && res.data.code === "success") {
                this.$message.success("提交成功")
              }
              this.getUrllist();
            } catch (e) {
              this.$message.error('连接服务器失败')
            }
            this.dialogVisible = false
          }
        );
      },
      getQueryList() {
      },
    },
    watch: {
      queryInfo() {
        //删除文字  清零
        if (!this.queryInfo) {
          this.listdata = this.listdata1
          return
        }
        this.timer = setTimeout(() => {
          const result = []
          this.listdata1.forEach(val => {
            if (val.url.indexOf(this.queryInfo) > -1) {
              result.push(val)
            } else if (val.title.indexOf(this.queryInfo) > -1) {
              result.push(val)
            }
          });
          this.listdata = result
          //console.log(this.cityList)
        }, 100)
      }
    },
  }
</script>

<style lang="less" scoped>

  #div_heard {
    height: 50px;
    /*background: #99CC66;*/

    /deep/ .el-dialog__wrapper {
      .el-dialog {
        .el-dialog__header {
          background: #409EFF;
          color: white;
        }

        .el-dialog__title {
          color: white;
          font-weight: bold;
        }

        .el-dialog__close {
          color: white;
        }

        .el-form {
          .el-form-item__cont {
            flex: 1;
          }
        }

      }
    }

  }

  #listdiv {
    width: fit-content;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: center;

  }

  #listdiv > div {
    width: 150px;
    height: 150px;
    margin: 10px;
  }

  .el-card:hover {
    margin-top: -5px;
    cursor: pointer;
    background: #89d68f;
  }

  .el-card div {
    display: flex;
    align-items: center;
  }

  .el-card span {
    font-weight: bolder;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    flex: 1;
    /*width: 100px;*/
  }

  .el-card span:hover {
    cursor: default;

  }

  #more {
    /*flex: 1;*/
    /*margin-right: 5px;*/
  }

  #more:hover {
    color: #409EFF;
    cursor: default;
  }

  .el-card:active {
    background: #409EFF;
  }

  .image {
    width: 100%;
    height: 120px;
    /*display: block;*/
  }


</style>
